package top.malaoshi.netdisk.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonResult<T> {
    private int code;
    private String msg;
    private T data;
    public JsonResult(int code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public JsonResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 校验失败
     * @param msg
     * @return
     */
    public static JsonResult validateFail(String msg){
        JsonResult jr=new JsonResult(JsonCodeMsg.VALIDATE_FAIL.getCode(), msg);
        return jr;
    }
    /**
     * 服务器出现错误
     * @return
     */
    public static JsonResult serverError(){
        JsonResult jr=new JsonResult(JsonCodeMsg.SERVER_ERROR.getCode(), JsonCodeMsg.SERVER_ERROR.getMsg());
        return jr;
    }
    /**
     * 服务器出现错误
     * @return
     */
    public static JsonResult serverError(String msg){
        JsonResult jr=new JsonResult(JsonCodeMsg.SERVER_ERROR.getCode(),msg);
        return jr;
    }
    /**
     * 表示执行成功
     * @param msg
     * @param data 数据
     * @return
     */
    public static JsonResult success(String msg,Object data){
        JsonResult jr=new JsonResult(JsonCodeMsg.SUCCESS.getCode(), msg,data);
        return jr;
    }
    public static JsonResult success(String msg){
        JsonResult jr=new JsonResult(JsonCodeMsg.SUCCESS.getCode(),msg);
        return jr;
    }

    /**
     * 操作失败
     * @param code
     * @param msg
     * @return
     */
    public static JsonResult fail(int code,String msg){
        JsonResult jr=new JsonResult(code,msg);
        return jr;
    }
    public static JsonResult fail(int code,String msg,Object data){
        JsonResult jr=new JsonResult(code,msg,data);
        return jr;
    }
    public String toJSON() throws JsonProcessingException {
        ObjectMapper om=new ObjectMapper();
        String jsonStr=om.writeValueAsString(this);
        return jsonStr;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}
